<?php


namespace app\api\service\order;

use app\api\model\Currency;
use app\api\model\User;
use app\api\model\UserCurrencyOrder;
use app\api\service\Token;
use think\Db;
use think\facade\Log;

class UserCurrencySer extends Token
{
    /**
     * 订单信息
     */
    protected $order;

    /**
     * 用户信息
     */
    protected $user;

    /**
     * 入口方法
     */
    public function entrance($order)
    {
        Log::init([
            'type' => 'File'
        ]);
        $this->order = $order;
        $this->user = User::where('openid',$this->order['openid'])->find();
        return $this->judgeOrder();
    }

    /**
     * 判断订单信息
     */
    protected function judgeOrder()
    {
        Db::startTrans();
        try{
            UserCurrencyOrder::where('id',$this->order['id'])->update([
                'status' => 2,
                'pay_time' => time(),
            ]);
            $this->changeUserCurrency();
            Db::commit();
            return true;
        } catch (\Exception $e){
            Db::rollback();
            Log::write('会员卡订单回调:'.$e,'error');
            return false;
        }
    }

    /**
     * 修改用户甜茶币
     */
    protected function changeUserCurrency()
    {
        $currency = $this->user['currency'] + $this->order['price'];
        User::where('openid',$this->user['openid'])->update([
            'currency' => $currency
        ]);
        Currency::create([
            'openid' => $this->user['openid'],
            'number' => $this->order['itself'] + $this->order['give'],
            'type' => 1,
            'status' => 8,
            'msg_json' => json_encode(UserCurrencyOrder::get($this->order['id']))
        ]);
    }
}